package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.interfaces.SetmealService;
import cn.itcast.pojo.PageResult;
import cn.itcast.pojo.QueryPageBean;
import cn.itcast.pojo.Result;
import cn.itcast.pojo.Setmeal;
import cn.itcast.utils.QiniuUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author: peterChen
 * @date: 2019/8/13 20:12
 * @description: TODO
 * @version: 1.0
 */
@RestController
@RequestMapping("setmeal")
public class SetmealController {
    @Reference
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;

    private Logger log = Logger.getLogger(SetmealController.class);

    /**
     * 上传文件（图片）
     * @param imgFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile")MultipartFile imgFile){
        try {
            //获取文件的名称
            String originalFilename = imgFile.getOriginalFilename();
            //获取文件后缀 . 的索引
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件的后缀
            String suffix = originalFilename.substring(lastIndexOf);
            //UUID随机创建文件名+后缀
            String filename = UUID.randomUUID().toString()+suffix;
            //利用七牛工具类上传该文件
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),filename);
            //上传成功，并将上传的文件名缓存入redis
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,filename);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,filename);

        } catch (IOException e) {
            //e.printStackTrace();
            log.error("upload pic error.",e);
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 添加套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("add setmeal error.",e);
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    /**
     * 分页查询套餐数据
     * @param queryPageBean
     * @return
     */
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @RequestMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        try {
            PageResult pageResult = setmealService.pageQuery(
                    queryPageBean.getCurrentPage(),
                    queryPageBean.getPageSize(),
                    queryPageBean.getQueryString()
            );
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,pageResult);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("query setmeal by page error.",e);
            return new Result(false,MessageConstant.QUERY_SETMEALLIST_FAIL);
        }
    }

    /**
     * 根据id获取对应套餐数据
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @RequestMapping("/findSetmealById")
    public Result findSetmealById(Integer id){
        try {
            Setmeal setmeal = setmealService.findSetmealById(id);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        } catch (Exception e) {
           // e.printStackTrace();
            log.error("query setmeal by id error.",e);
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    /**
     * 根据套餐id获取关联检查组id
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    @RequestMapping("/findCheckgroupIdsBySetmealId")
    public Result findCheckgroupIdsBySetmealId(Integer id){

            List<Integer> checkgroupIds =  setmealService.findCheckgroupIdsBySetmealId(id);
            if(!CollectionUtils.isEmpty(checkgroupIds)  && checkgroupIds.size()>0) {
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, checkgroupIds);
            }
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
    }

    /**
     * 提交编辑后的套餐信息，并重新关联对应的检查组
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @PreAuthorize("hasAuthority('SETMEAL_EDIT')")
    @RequestMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try {
            setmealService.edit(setmeal,checkgroupIds);
            return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("edit setmeal error.",e);
            return new Result(false,MessageConstant.EDIT_SETMEAL_FAIL);
        }
    }

    /**
     * 删除对应套餐
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('SETMEAL_DELETE')")
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            setmealService.delete(id);
            return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("delete setmeal error.",e);
            return new Result(false,MessageConstant.DELETE_SETMEAL_FAIL);
        }
    }
}
